package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.FormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Bid;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ChanceDeliveryTemp;
import com.sl.au.entity.ChanceFlowNode;
import com.sl.au.entity.Customer;
import com.sl.au.entity.ExdeviExdePersonRoleInfo;
import com.sl.au.entity.JPushMsg;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.SectionArea;
import com.sl.au.entity.User;
import com.sl.au.repository.ChanceRepository;
import com.sl.au.service.ChanceDeliveryService;
import com.sl.au.service.ChanceFlowNodeService;
import com.sl.au.service.ChanceKeyManService;
import com.sl.au.service.ChanceService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.ExdeviExdePersonRoleInfoService;
import com.sl.au.service.JGPushService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.SectionService;
import com.sl.utils.ExdeUtil;

@RestController
@RequestMapping(value = "/ui/chance")
public class ChanceController extends BaseController {
	
	@Autowired
	CustomerService customerService;
	
	@Autowired
	ChanceService chanceService;
	
	@Autowired
	SaleAreaService saleAreaService;
	
	@Autowired
	ChanceDeliveryService chanceDeliveryService;
	
	@Autowired
	ChanceKeyManService chanceKeyManService;
	
	@Autowired
	ChanceRepository chanceRepository;
	
	@Autowired
	OperateLogService operateLogService;
	
	@Autowired
	ChanceFlowNodeService chanceFlowNodeService;
	
	@Autowired
	JGPushService jPushService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	ExdeviExdePersonRoleInfoService exdeviExdePersonRoleInfoService;
	
	@Autowired
	SectionService sectionService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("chance/chanceindex");
		
		return modelAndView;
	}
	/**
	 * 客户的销售信息服务器分页数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getcustomerchance", method = RequestMethod.GET)
	public Map<String,Object> getCustomerChance(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String customerId = request.getParameter("customerId");
		String key=request.getParameter("key");
		List<Chance> saleChances = new ArrayList<Chance>();
		saleChances=chanceService.getCustomerChances(start, length, customerId, key);
		long count=chanceService.getCustomerChancesCount(customerId, key);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 销售信息服务器分页数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> condition = new HashMap<String,String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String state = request.getParameter("state");
		if(key == null){key ="";}
		Account a = this.getMyAccount();
		String userId=a.getUser().getId();
		condition.put("key", key);
		condition.put("state", state);
		condition.put("userId", userId);
		List<Chance> saleChances = chanceService.getSaleChances(start, length, condition, "createTime", "desc");
		int count = chanceService.getSaleChanceCount(condition);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 销售信息登记表页面
	 * @return
	 */
	@RequestMapping(value = "/chanceRegister")
	public ModelAndView saleChanceRegister() {
		ModelAndView modelAndView = this.createLayoutView("chance/chanceRegister");
		String businessGroup = "行业";
		Account a = this.getMyAccount();
		String userName=a.getUser().getName();
		String userId=a.getUser().getId();
		String userSuperior=a.getUser().getSaleArea().getSuperior();
		String userSuperiorArea=a.getUser().getSaleArea().getSuperiorArea();
		List<SaleArea> saleAreas = saleAreaService.getRepository().getAllSaleArea();
		List<SaleArea> peosaleAreas = saleAreaService.getRepository().findBySuperior(a.getUser().getSaleArea().getSuperior());
		List<Option> businesses = optionService.getRepository().findByGroup(businessGroup);
		modelAndView.addObject("businesses", businesses);
		modelAndView.addObject("userName", userName);
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("userSuperior", userSuperior);
		modelAndView.addObject("saleAreas", saleAreas);
		modelAndView.addObject("peosaleAreas", peosaleAreas);
		modelAndView.addObject("userSuperiorArea", userSuperiorArea);
		return modelAndView;
	}
	
	/**
	 * 移动端获取订货单位名称
	 * @return
	 */
	@RequestMapping(value="/mobileGetCustomer",method=RequestMethod.GET)
	public Map<String, Object> mobileGetCustomer(){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Customer> customers = customerService.getRepository().findAll();
		map.put("customers", customers);
		return map;
	}
	/**
	 * 移动端获取订货单位所属片区
	 * @return
	 */
	@RequestMapping(value = "/mobileGetSaleArea",method=RequestMethod.GET)
	public Map<String, Object> mobileGetSaleArea() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<SaleArea> saleAreas = saleAreaService.getRepository().getAllSaleArea();
		map.put("saleAreas", saleAreas);
		return map;
	}
	/**
	 * 信息登记表登记保存
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveSaleChance(HttpServletRequest request, @RequestBody Chance saleChance) {
		String buss = saleChance.getBusiness();
		System.out.println(buss);
		System.out.println(saleChance.getUser());
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtils.hasText(saleChance.getId())) {
			saleChance.setId(java.util.UUID.randomUUID().toString());
			}
		chanceService.getRepository().save(saleChance);
		//保存日志
		Account a = this.getMyAccount();
		String chanceId=saleChance.getId();
		User user=a.getUser();
		String chanceName=saleChance.getName();
		String content = "新增销售信息【"+chanceName+"】";
		operateLogService.log(user, "信息登记", content);
		map.put("code", 0);
		map.put("chanceId", chanceId);
		return map;
	}
	/**
	 * 机会登记表编辑页面
	 * @return
	 */
	@RequestMapping(value = "/edit",method = RequestMethod.GET)
	public ModelAndView saleChanceEdit(HttpServletRequest request) {
		ModelAndView modelAndView = this.createLayoutView("chance/chanceRegisterEdit");
		String chanceId = request.getParameter("chanceId");
		String businessGroup = "行业";
		Chance saleChance = chanceService.getRepository().findOne(chanceId);
		Account a = this.getMyAccount();
		String userSuperior=a.getUser().getSaleArea().getSuperior();
		//Customer customer = customerService.getRepository().findById(chanceId1);
		List<SaleArea> saleAreas = saleAreaService.getRepository().getAllSaleArea();
		List<SaleArea> peosaleAreas = saleAreaService.getRepository().findBySuperior(a.getUser().getSaleArea().getSuperior());
		List<Option> businesses = optionService.getRepository().findByGroup(businessGroup);
		modelAndView.addObject("businesses", businesses);
		modelAndView.addObject("saleChance", saleChance);
		modelAndView.addObject("userSuperior", userSuperior);
		modelAndView.addObject("saleAreas", saleAreas);
		modelAndView.addObject("peosaleAreas", peosaleAreas);
		return modelAndView;
	}
	
	/**
	 * 信息提交
	 * @return
	 */
	@RequestMapping(value = "/submitChance",method = RequestMethod.POST)
	public Map<String,Object> submitChance(HttpServletRequest request, @RequestBody ChanceDeliveryTemp chanceDeliveryTemp) {
		Map<String, Object> map = new HashMap<String, Object>();
		chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
		String chanceId=chanceDeliveryTemp.getSaleChance().getId();
		Account a = this.getMyAccount();
		User user=a.getUser();
		
		if(chanceId !=null){
			Chance saleChance = chanceService.getRepository().findOne(chanceId);
			
			//获取创建人片区和部门
			String superior = saleChance.getUser().getSaleArea().getSuperior();
			String areaName = saleChance.getUser().getSaleArea().getAreaName();
			List<String> list = new ArrayList<>();
			List<SectionArea> sectionAreas = sectionService.findSectionAreaOne(superior, areaName);
			if(sectionAreas.size()>0){
				for(SectionArea sectionArea : sectionAreas)
					list.add(ExdeUtil.splitString(sectionArea.getSection().getChief().getId()));
			}
			System.out.println("科长"+sectionAreas.size());
			List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("处长", superior);
			for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
				list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
			}
			System.out.println("处长"+exdeviExdePersonRoleInfos.size());
			
			if(saleChance != null){
				saleChance.setIsSubmit(1);
				chanceService.getRepository().save(saleChance);
				String chanceName=saleChance.getName();
				
				JPushMsg msg = new JPushMsg();
				msg.setAlias(list);
				msg.setContent("信息待处理：来自" + user.getName() + "提交" + chanceName);
				msg.setTitle("信息" + chanceName);
				Map<String, String> extras = new HashMap<>();
				extras.put("ex1", "附加内容1");
				extras.put("ex2", "附加内容2");
				
				String content = "提交销售信息【"+chanceName+"】";
				operateLogService.log(user, "信息登记", content);
				
				//写入流转记录
				chanceFlowNodeService.flow(user, saleChance, user.getName(), user.getSaleArea().getSuperior(),"信息提交");
				jPushService.sendClient(msg, extras);
			}
		}
		map.put("code", 0);
		return map;
	}
	//删除信息
	@RequestMapping(value = "/deleteChance", method = RequestMethod.GET)
	public Map<String, Object> delBid(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
	    String ids=request.getParameter("ids");
	    String id[]=ids.split(",");
	    List<Chance> Chances=new ArrayList<Chance>();
	    Account a = this.getMyAccount();
		//保存日志
		User user=a.getUser();
		
	    for(int i=0;i<id.length;i++){
	    	String chanceId = id[i];
	    	Chance Chance=new Chance();
	    	Chance.setId(chanceId);
	    	Chances.add(Chance);
	    chanceKeyManService.getRepository().deleteChanceKeyMan(chanceId);//删除信息前先删除相关的信息关键人物
	    Chance= chanceService.getRepository().findOne(chanceId);
	    String chanceName=Chance.getName();
		String content = "删除销售信息【"+chanceName+"】";
		operateLogService.log(user, "信息登记", content);
	    }
	    chanceService.getRepository().deleteInBatch(Chances);
		map.put("code", 0);
		return map;	
	}
	/**
	 * 机会（信息）详情页面
	 * @return
	 */
	@RequestMapping(value = "/detail",method = RequestMethod.GET)
	public ModelAndView saleChanceDetail(HttpServletRequest request) {
		ModelAndView modelAndView = this.createLayoutView("chance/chanceDetail");
		String chanceId = request.getParameter("chanceId");
		String businessGroup = "行业";
		List<ChanceFlowNode> nodes = chanceFlowNodeService.getFlows(chanceId);
		Chance saleChance =chanceService.getRepository().findOne(chanceId);
		List<Option> businesses = optionService.getRepository().findByGroup(businessGroup);
		modelAndView.addObject("businesses", businesses);
		modelAndView.addObject("chanceId", chanceId);
		modelAndView.addObject("saleChance", saleChance);
		modelAndView.addObject("nodes", nodes);
		return modelAndView;
	}
	/**
	 * 移动端获取信息流转
	 * @return
	 */
	@RequestMapping(value = "/mobileFlowNode",method = RequestMethod.GET)
	public Map<String, Object> mobileSaleChanceNode(HttpServletRequest request) {
		Map<String, Object>map=new HashMap<>();
		String chanceId = request.getParameter("chanceId");
		List<ChanceFlowNode> nodes = chanceFlowNodeService.getFlows(chanceId);
		map.put("nodes", nodes);
		return map;
	}
	
	/**
	 * 写入信息流转记录
	 * @return
	 */
	@RequestMapping(value = "/flow", method = RequestMethod.POST)
	public Map<String, Object> chanceFlow(HttpServletRequest request, @RequestBody ChanceFlowNode node) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		//写入流转记录
		chanceFlowNodeService.flow(user, node.getChance(), user.getName(),node.getEndNode(),node.getFlowOperate());
		map.put("code", 0);
		return map;
	}
}
